package admin

import (
	"XSSS_v2/handler"
	"XSSS_v2/model"
	"XSSS_v2/pkg/auth"
	"XSSS_v2/pkg/errno"
	"XSSS_v2/pkg/token"
	"github.com/gin-gonic/gin"
)

// Login
// @Summary 用户登录
// @Param admin body model.Admin true "admin info"
// @Produce json
// @Success 200 {object} handler.Response
// @Router /login [post]
func Login(c *gin.Context) {
	var r RegisnerRequest
	//绑定参数
	err := c.Bind(&r)
	/*name := c.Query("username")
	pwd := c.Query("pwd")*/
	if err != nil {
		handler.SendResponse(c, errno.ErrBind, nil)
		return
	}

	//查是否有这个人
	admin, err := model.GetAdmin(r.Username)
	if err != nil {
		handler.SendResponse(c, errno.ErrAdminNotFound, nil)
		return
	}

	//验证密码是否一致
	if err := auth.Compare(admin.Apwd, r.Password); err != nil {
		handler.SendResponse(c, errno.ErrPasswordIncorrect, nil)
		return
	}
	//发送token
	tokenString, err := token.Sign(token.Context{Username: admin.Aname, Obj: "stuTable"}, "")
	if err != nil {
		handler.SendResponse(c, errno.ErrToken, nil)
		return
	}

	//正确响应
	handler.SendResponse(c, nil, model.Token{tokenString})
}
